﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickGraph.Graphviz;
using QuickGraph.Graphviz.Dot;

namespace GxcToCsharpParser.Utility
{
   public class QuickGraphDotEngine: IDotEngine
   {
      #region IDotEngine Members



      /// <summary>
      /// Generates a dot file and its  image.
      /// </summary>
      /// <param name="imageType">Type of the image.</param>
      /// <param name="dot">The dot.</param>
      /// <param name="outputFileName">Name of the output file.</param>
      /// <returns></returns>
      public string Run(GraphvizImageType imageType, string dot, string outputFileName)
      {
         string path = outputFileName;
         if (!path.EndsWith(".dot", StringComparison.InvariantCultureIgnoreCase))
         {
            path = path + ".dot";
         }
         System.IO.File.WriteAllText(path, dot);

         DotToImageEngine.GenereateImageFromDotFile(imageType, path);
        
         return path;


      }
     



      #endregion

   }
   public class DotToImageEngine
   {
      public static void GenereateImageFromDotFile(string path)
      {
         GenereateImageFromDotFile(GraphvizImageType.Png, path);
      }
      public static void GenereateImageFromDotFile(GraphvizImageType imageType, string path)
      {
         using (System.Diagnostics.Process process = new System.Diagnostics.Process())
         {

            //We'll launch dot.exe in command line

            process.StartInfo.FileName = @"C:\Program Files\Graphviz2.24\bin\dot.exe";

            //Let's give the type we want to generate to, and a charset

            //to support accent

            process.StartInfo.Arguments = string.Format("-T{0} -Gcharset=latin1 -O {1}", imageType.ToString().ToLower(), path);

            //We'll receive the bitmap thru the standard output stream

            process.StartInfo.RedirectStandardOutput = true;

            //We'll need to give the dot structure in the standard input stream

            process.StartInfo.RedirectStandardInput = false;

            process.StartInfo.UseShellExecute = false;

            process.Start();



            //Wait the process is finished and get back the image (binary format)

            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();



         }
      }
   }
}
